package com.lc.file.utils;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;

import com.lc.file.config.RichTextConfig;
import com.study.common.constant.LocalConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.*;


/**
 * @description: 富文本转存工具
 * @author: LChuang
 * @date: 2023/12/1 13:41
 */
@Slf4j
public class RichTextFileUtils {

    /**
     * 富文本转txt文件，返回uuid文件名
     */
    public static String richTextToFile(String text) {
        OutputStream outputStream = null;
        try {
            String folder = RichTextConfig.getFolder();
            String fileName = getRandomFileName(LocalConstant.TXT_SUFFIX);
            String uuid = fileName.substring(0, fileName.lastIndexOf(LocalConstant.POINT));
            String filePath;
            if (StrUtil.isNotEmpty(folder)) {
                filePath = StrUtil.appendIfMissing(folder, LocalConstant.LEFT_SLASH) + fileName;
            } else {
                filePath = fileName;
            }
            File dest = new File(System.getProperty("user.dir") + File.separator + filePath);
            if (!dest.getParentFile().exists()) {
                boolean result = dest.getParentFile().mkdirs();
                log.info(result ? "创建父级目录成功" : "创建父级目录失败");
                if (!dest.exists()) {
                    boolean newFile = dest.createNewFile();
                    log.info(newFile ? "创建父级目录成功" : "创建父级目录失败");
                }
            }
            outputStream = new FileOutputStream(filePath);
            outputStream.write(text.getBytes());
            log.info("text转存文件成功，文件名uuid：{}", uuid);
            return uuid;
        } catch (IOException e) {
            log.error("text转存文件失败");
            ExceptionUtil.stacktraceToString(e);
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException ioE) {
                    log.error(ioE.getMessage());
                }
            }
        }
        return StrUtil.EMPTY;
    }

    /**
     * uuid文件编号转富文本
     */
    public static String fileToRichText(String uuid) {
        if (StrUtil.isEmpty(uuid)) {
            return StrUtil.EMPTY;
        }
        String folder = RichTextConfig.getFolder();
        String filePath;
        if (StrUtil.isNotEmpty(folder)) {
            filePath = StrUtil.appendIfMissing(folder, LocalConstant.LEFT_SLASH) + uuid + LocalConstant.TXT_SUFFIX;
        } else {
            filePath = uuid + LocalConstant.TXT_SUFFIX;
        }
        File dest = new File(System.getProperty("user.dir") + File.separator + filePath);
        if (!dest.exists()) {
            log.error("{} 文件不存在", filePath);
            return StrUtil.EMPTY;
        }
        return readAsString(filePath);
    }

    /**
     * 根据uuid删除转存的富文本文件
     */
    public static boolean removeText(String uuid) {
        String folder = RichTextConfig.getFolder();
        String filePath;
        if (StrUtil.isNotEmpty(folder)) {
            filePath = StrUtil.appendIfMissing(folder, LocalConstant.LEFT_SLASH) + uuid + LocalConstant.TXT_SUFFIX;
        } else {
            filePath = uuid + LocalConstant.TXT_SUFFIX;
        }
        File dest = new File(filePath);
        if (!dest.exists()) {
            log.error("{}文件不存在", uuid);
        }
        return dest.delete();

    }


    /**
     * 通过BufferedReader读取
     *  path 文件的本地绝对路径
     */
    public static String readAsString(String path) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(path));
            StringBuilder stringBuilder = new StringBuilder();
            String line = null;
            String ls = System.getProperty("line.separator");
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
                stringBuilder.append(ls);
            }
            // 删除最后一个新行分隔符
            stringBuilder.delete(stringBuilder.length() - ls.length(), stringBuilder.length());
            return stringBuilder.toString();
        } catch (Exception exception) {
            log.error("readAsString error,path={},exception={}", path, ExceptionUtils.getStackTrace(exception));
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ioE) {
                    log.error(ioE.getMessage());
                }

            }
        }
        return StrUtil.EMPTY;
    }


    /**
     * 更新txt文件
     */
    public static String updateRichTextFile(String uuid, String text) {
        try {
            String folder = RichTextConfig.getFolder();
            String filePath;
            if (StrUtil.isNotEmpty(folder)) {
                filePath = StrUtil.appendIfMissing(folder, LocalConstant.LEFT_SLASH) + uuid + LocalConstant.TXT_SUFFIX;
            } else {
                filePath = uuid + LocalConstant.TXT_SUFFIX;
            }
            File dest = new File(filePath);
            if (!dest.getParentFile().exists()) {
                log.error("文件父级目录不存在");
                return StrUtil.EMPTY;
            }
            if (!dest.exists()) {
                log.error("{}文件不存在", uuid);
                return StrUtil.EMPTY;
            }
            OutputStream outputStream = new FileOutputStream(filePath);
            outputStream.write(text.getBytes());
            log.info("uuid：{} 富文本更新成功", uuid);
            return uuid;
        } catch (IOException e) {
            log.error("uuid：{} text文件更新失败", uuid);
        }
        return StrUtil.EMPTY;
    }

    public static String getRandomFileName(String suffix) {
        return IdUtil.fastSimpleUUID() + suffix;
    }


    public static String extractText(String html) {
        Document document = Jsoup.parse(html);
        Elements elements = document.body().select("*");
        StringBuilder sb = new StringBuilder();
        for (Element element : elements) {
            sb.append(element.ownText()).append(" ");
        }
        String trim = sb.toString().trim();
        return trim.substring(0, (Math.min(trim.length(), LocalConstant.HUNDRED)));
    }

}
